package com.xca.znb.view;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.entity.Goods;
import com.xca.znb.entity.Order;
import com.xca.znb.model.impl.OrdersImpl;
import com.xca.znb.presenter.OrdersPresenter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class OrdersActivity extends AppCompatActivity{
    private ImageView Back ;
    private TextView BuyEnter , SaleOut ,AllOrders , WaitShipments , WaitReceiving , Done , AfterSales ;
    private ListView OrderList ;
    private List<Order> listOrder ;
    private ArrayAdapter<Order> adapter ;
    private OrdersPresenter presenter ;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.orders);
        Back = findViewById(R.id.orders_back) ;
        BuyEnter = findViewById(R.id.orders_buy_enter) ;
        SaleOut = findViewById(R.id.orders_sale_out) ;
        AllOrders = findViewById(R.id.orders_all_order) ;
        WaitShipments = findViewById(R.id.orders_wait_shipments) ;
        WaitReceiving = findViewById(R.id.orders_wait_receiving) ;
        Done = findViewById(R.id.orders_done) ;
        AfterSales = findViewById(R.id.orders_after_sales) ;
        OrderList = findViewById(R.id.orders_show_list) ;


        OrdersImpl ordersImpl = new OrdersImpl(this);
        presenter = new OrdersPresenter(ordersImpl);

        Bundle getIntent = getIntent().getExtras();
        if (getIntent != null){
            int caseOrder = getIntent.getInt("case");
            if (caseOrder <= 5){
                BuyEnter.setSelected(true);
                if (caseOrder == 1){
                    AllOrders.setSelected(true);
                } else if (caseOrder == 2) {
                    WaitShipments.setSelected(true);
                } else if (caseOrder == 3) {
                    WaitReceiving.setSelected(true);
                } else if (caseOrder == 4) {
                    Done.setSelected(true);
                } else if (caseOrder == 5) {
                    AfterSales.setSelected(true);
                }
            }else {
                SaleOut.setSelected(true);
                AllOrders.setSelected(true);
            }
        }

        BuyEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BuyEnter.setSelected(true);
                SaleOut.setSelected(false);
                refreshData();
            }
        });
        SaleOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BuyEnter.setSelected(false);
                SaleOut.setSelected(true);
                refreshData();
            }
        });
        AllOrders.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AllOrders.setSelected(true);
                WaitShipments.setSelected(false);
                WaitReceiving.setSelected(false);
                Done.setSelected(false);
                AfterSales.setSelected(false);
                refreshData();
            }
        });
        WaitShipments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AllOrders.setSelected(false);
                WaitShipments.setSelected(true);
                WaitReceiving.setSelected(false);
                Done.setSelected(false);
                AfterSales.setSelected(false);
                refreshData();
            }
        });

        WaitReceiving.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AllOrders.setSelected(false);
                WaitShipments.setSelected(false);
                WaitReceiving.setSelected(true);
                Done.setSelected(false);
                AfterSales.setSelected(false);
                refreshData();
            }
        });
        Done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AllOrders.setSelected(false);
                WaitShipments.setSelected(false);
                WaitReceiving.setSelected(false);
                Done.setSelected(true);
                AfterSales.setSelected(false);
                refreshData();
            }
        });
        AfterSales.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AllOrders.setSelected(false);
                WaitShipments.setSelected(false);
                WaitReceiving.setSelected(false);
                Done.setSelected(false);
                AfterSales.setSelected(true);
                refreshData();
            }
        });
        Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void getData(){
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");

        LocalDateTime nowTime = LocalDateTime.now();
        String secTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String dayTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        if (BuyEnter.isSelected()){
            if (AllOrders.isSelected()){
                listOrder = presenter.getAllOrderBuy(phone);
            } else if (WaitShipments.isSelected()) {
                listOrder = presenter.getOrderBuy(phone,"待发货");
            } else if (WaitReceiving.isSelected()) {
                listOrder = presenter.getOrderBuy(phone,"待收货");
            } else if (Done.isSelected()) {
                listOrder = presenter.getOrderBuy(phone,"已完成");
            } else if (AfterSales.isSelected()) {
                listOrder = presenter.getOrderBuy(phone,"已退款");
            }
        } else if (SaleOut.isSelected()) {
            if (AllOrders.isSelected()){
                listOrder = presenter.getAllOrderSale(phone);
            } else if (WaitShipments.isSelected()) {
                listOrder = presenter.getOrderSales(phone,"待发货");
            } else if (WaitReceiving.isSelected()) {
                listOrder = presenter.getOrderSales(phone,"待收货");
            } else if (Done.isSelected()) {
                listOrder = presenter.getOrderSales(phone,"已完成");
            } else if (AfterSales.isSelected()) {
                listOrder = presenter.getOrderSales(phone,"已退款");
            }
        }

        adapter = new ArrayAdapter<Order>(this , R.layout.order_list_item , R.id.order_show_goods_name , listOrder){
            public View getView(int position , View converView , ViewGroup parent){
                View view = super.getView(position,converView,parent);
                LinearLayout toMessage = view.findViewById(R.id.order_to_message);
                ImageView goodsImg = view.findViewById(R.id.order_goods_img_show);
                TextView goodsName = view.findViewById(R.id.order_show_goods_name);
                TextView orderId = view.findViewById(R.id.order_order_id);
                TextView goodsNum = view.findViewById(R.id.order_show_goods_num);
                TextView goodsPrice = view.findViewById(R.id.order_show_goods_price);
                TextView goodsUnit = view.findViewById(R.id.order_show_goods_unit);
                TextView payMoney = view.findViewById(R.id.order_show_pay_money);
                TextView orderType = view.findViewById(R.id.order_show_type);
                Button receive = view.findViewById(R.id.order_receive);
                Button refund = view.findViewById(R.id.order_refund);
                Order order = getItem(position);
                assert order != null;
                Goods goods = presenter.getGoodsById(order.getGoodsId());

                toMessage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(OrdersActivity.this , OrderMessage.class);
                        if (BuyEnter.isSelected()){
                            intent.putExtra("order_to_msg_type" , 1);
                        } else if (SaleOut.isSelected()) {
                            intent.putExtra("order_to_msg_type" , 2);
                        }
                        intent.putExtra("order_to_message_orderId" , order.getId());
                        startActivity(intent);
                    }
                });

                if (order != null){
                    Glide.with(OrdersActivity.this)
                                    .load(goods.getFirst_image())
                                            .into(goodsImg);
                    goodsName.setText(goods.getName());
                    orderId.setText(String.valueOf(order.getId()));
                    goodsNum.setText(String.valueOf(order.getNum()));
                    goodsPrice.setText(String.valueOf(goods.getPrice()));
                    goodsUnit.setText(goods.getUnit());
                    payMoney.setText(String.valueOf(goods.getPrice() * order.getNum()));
                    orderType.setText(order.getType());
                    if (BuyEnter.isSelected()){
                        if (order.getType().equals("待发货")){
                            receive.setVisibility(View.GONE);
                            refund.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    new AlertDialog.Builder(OrdersActivity.this)
                                            .setMessage("确定退款吗")
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    presenter.updateOrderType(order.getId() , "已退款",secTime);
                                                    Order order1 = presenter.getOrderById(order.getId());
                                                    if (order1.getType().equals("已退款")){
                                                        presenter.insertAccount(phone , goods.getPrice() * order.getNum() , "退款",dayTime,secTime);
                                                        presenter.insertAccount(order.getSales() , goods.getPrice() * order.getNum() , "买家退款",dayTime,secTime);
                                                        Toast.makeText(OrdersActivity.this, "退款成功", Toast.LENGTH_SHORT).show();

                                                    }else {
                                                        Toast.makeText(OrdersActivity.this, "退款失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                    refreshData();
                                                }
                                            })
                                            .setNegativeButton("取消", null)
                                            .create().show();
                                }
                            });
                        }else if (order.getType().equals("待收货")) {
                            receive.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    new AlertDialog.Builder(OrdersActivity.this)
                                            .setMessage("确定收货吗")
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    presenter.updateOrderType(order.getId() , "已完成",secTime);
                                                    Order order1 = presenter.getOrderById(order.getId());
                                                    if (order1.getType().equals("已完成")){
                                                        Toast.makeText(OrdersActivity.this, "收货完成", Toast.LENGTH_SHORT).show();
                                                    }else {
                                                        Toast.makeText(OrdersActivity.this, "收货失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                    refreshData();
                                                }
                                            })
                                            .setNegativeButton("取消", null)
                                            .create().show();
                                }
                            });
                            refund.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    new AlertDialog.Builder(OrdersActivity.this)
                                            .setMessage("确定退款吗")
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    presenter.updateOrderType(order.getId() , "已退款",secTime);
                                                    Order order1 = presenter.getOrderById(order.getId());
                                                    if (order1.getType().equals("已退款")){
                                                        presenter.insertAccount(phone , goods.getPrice() * order.getNum() , "退款",dayTime,secTime);
                                                        presenter.insertAccount(order.getSales() , goods.getPrice() * order.getNum() , "买家退款",dayTime,secTime);
                                                        Toast.makeText(OrdersActivity.this, "退款成功", Toast.LENGTH_SHORT).show();
                                                    }else {
                                                        Toast.makeText(OrdersActivity.this, "退款失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                    refreshData();
                                                }
                                            })
                                            .setNegativeButton("取消", null)
                                            .create().show();

                                }
                            });
                        } else if (order.getType().equals("已完成") || order.getType().equals("已退款")) {
                            receive.setVisibility(View.GONE);
                            refund.setVisibility(View.GONE);
                        }

                    } else if (SaleOut.isSelected()) {
                        if (order.getType().equals("待发货")){
                            receive.setText("发货");
                            receive.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    new AlertDialog.Builder(OrdersActivity.this)
                                            .setMessage("确定发货吗")
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    presenter.updateOrderType(order.getId() , "待收货",secTime);
                                                    Order order1 = presenter.getOrderById(order.getId());
                                                    if (order1.getType().equals("待收货")){
                                                        Toast.makeText(OrdersActivity.this, "发货完成", Toast.LENGTH_SHORT).show();
                                                    }else {
                                                        Toast.makeText(OrdersActivity.this, "发货失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                    refreshData();
                                                }
                                            })
                                            .setNegativeButton("取消", null)
                                            .create().show();
                                }
                            });
                            refund.setVisibility(View.GONE);
                        } else if (order.getType().equals("待收货") || order.getType().equals("已完成") || order.getType().equals("已退款")) {
                            receive.setVisibility(View.GONE);
                            refund.setVisibility(View.GONE);
                        }
                    }
                }
                return view ;
            }
        };
    }
    private void refreshData(){
        getData();
        OrderList.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshData();
    }

}
